from __future__ import with_statement

from google.appengine.api import memcache
from google.appengine.ext import blobstore
from google.appengine.api import files

import logging
import string 
import blobcache

def delete(blob_key):
    # delete from cache
    blobcache.delete(str(blob_key))
    
    # delete from blobstore
    logging.debug("Deleting blob value with key %s from blobstore" % str(blob_key))
    blob_info = blobstore.BlobInfo.get(blob_key)
    if not blob_info:
        return False 
    blob_info.delete()
    return True

def save(filename, content):
    logging.debug("Saving file %s to blobstore" % filename)
     # Create the file
    file_name = files.blobstore.create(mime_type='application/x-mobipocket-ebook', _blobinfo_uploaded_filename=filename)
    # Open the file and write to it
    with files.open(file_name, 'a') as f:
        f.write(content)
    # Finalize the file. Do this before attempting to read it.
    files.finalize(file_name)
    # Get the file's blob key
    blob_key = files.blobstore.get_blob_key(file_name)
    
    # save to cache as well
    blobcache.set(str(blob_key), content)
    
    return blob_key


def load(blob_key): 
    # try cache first
    cached_content = blobcache.get(str(blob_key))    
    if cached_content:
        logging.debug("Blob value with key %s from cache" % str(blob_key))
        return cached_content
    
    # get data from blobstore
    logging.debug("Retrieving blob value with key %s from blobstore" % str(blob_key))
    blob_info = blobstore.BlobInfo.get(blob_key)
    if not blob_info:
        raise Exception('Blob Key does not exist')
    
    blob_file_size = blob_info.size   
    
    blob_concat = ""
    start = 0
    end = blobstore.MAX_BLOB_FETCH_SIZE - 1
    step = blobstore.MAX_BLOB_FETCH_SIZE - 1
    
    while(start < blob_file_size):        
        blob_concat += blobstore.fetch_data(blob_key, start, end)
        temp_end = end
        start = temp_end + 1
        end = temp_end + step
        
    return blob_concat